# Maintainer: David Grayson <davidegrayson@gmail.com>

_realname=avrdude
pkgbase=mingw-w64-${_realname}
pkgname="${MINGW_PACKAGE_PREFIX}-${_realname}"
pkgver=8.0
pkgrel=2
pkgdesc='Download/upload/manipulate the ROM and EEPROM contents of AVR microcontrollers (mingw-w64)'
arch=('any')
mingw_arch=('mingw64' 'ucrt64' 'clang64' 'clangarm64')
url="https://github.com/avrdudes/avrdude"
license=('spdx:GPL-2.0-or-later')
makedepends=("${MINGW_PACKAGE_PREFIX}-cc"
             "${MINGW_PACKAGE_PREFIX}-cmake"
             "${MINGW_PACKAGE_PREFIX}-libelf"
             "${MINGW_PACKAGE_PREFIX}-ninja")
depends=("${MINGW_PACKAGE_PREFIX}-hidapi"
         "${MINGW_PACKAGE_PREFIX}-libftdi"
         "${MINGW_PACKAGE_PREFIX}-libserialport"
         "${MINGW_PACKAGE_PREFIX}-libusb-compat"
         "${MINGW_PACKAGE_PREFIX}-libusb"
         "${MINGW_PACKAGE_PREFIX}-ncurses"
         "${MINGW_PACKAGE_PREFIX}-readline")
         # "${MINGW_PACKAGE_PREFIX}-python"
         # "${MINGW_PACKAGE_PREFIX}-swig"
         # "${MINGW_PACKAGE_PREFIX}-termcap"
options=('strip')
source=("https://github.com/avrdudes/avrdude/releases/download/v${pkgver}/avrdude-${pkgver}.tar.gz"
        "0001-shared-build-fix.patch"
        "0002-missing-include.patch")
sha256sums=('a689d70a826e2aa91538342c46c77be1987ba5feb9f7dab2606b8dae5d2a52d5'
            'bcd9fd678c619d0792e6b9346609461a880ae659fd4b5439c465837275243158'
            '33626a6d87f75d6f3baa376283bcee9a122ef2e03c40e2bb3e55de764a09e862')
validpgpkeys=('EF497ABE47ED91B3FC3D7EA54D902FF7723BDEE9'  # Brian Dean <bsd@bdmicro.com>
              '5E84F980C3CAFD4BB5841070F48CA81B69A85873'  # Joerg Wunsch <j@uriah.heep.sax.de>
              '56628323218C669FF578705C7E9EADC3030D34EB'  # Joerg Wunsch <joerg_wunsch@uriah.heep.sax.de>
              '8FBDC99556F7C22A77DC3E1145684AB70D286F63') # Stefan Rueger <stefan.rueger@urclocks.com>

# Helper macros to help make tasks easier #
apply_patch_with_msg() {
  for _patch in "$@"; do
    msg2 "Applying ${_patch}"
    patch -Nbp1 -i "${srcdir}/${_patch}"
  done
}
# =========================================== #

prepare() {
  cd "${_realname}-${pkgver}"

  apply_patch_with_msg 0001-shared-build-fix.patch
  # https://github.com/avrdudes/avrdude/issues/1940
  apply_patch_with_msg 0002-missing-include.patch
}

build() {
  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    cmake -B "build-${MSYSTEM}" -S "${_realname}-${pkgver}" -G "Ninja" \
      -DCMAKE_INSTALL_PREFIX=${MINGW_PREFIX} \
      -DCMAKE_C_FLAGS_INIT="-I${MINGW_PREFIX}/include/libusb-compat" \
      -DUSE_STATIC_LIBS=OFF \
      "${extra_config[@]}"

  cmake --build "build-${MSYSTEM}"
}

package() {
  DESTDIR="${pkgdir}" cmake --install "build-${MSYSTEM}"

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/COPYING" -t "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}"
}
